/**
 * Description:
 * Class Name:FieldTest
 * Date:2022/4/30 16:43
 *
 * @author LTisme
 * @version JAVA17
 */
package 疯狂Java讲义.第18章_类加载机制与反射._18_4_使用反射生成并操作对象._18_4_3_访问成员变量;

import java.lang.reflect.Field;

class Person{
    private String name;
    private int age;
    public String toString(){
        return "Person [name=" + name + ", age=" + age + "]";
    }
}

public class FieldTest {
    public static void main(String[] args) throws Exception{
        // 创建一个Person对象
        var p = new Person();
        // 获取Person类对应的Class对象
        Class<Person> personClass = Person.class;
        // 获取Person类的名为name的成员变量，由于是private修饰，需要获取后再用setAccessible来取消权限检查
        Field nameField = personClass.getDeclaredField("name");
        nameField.setAccessible(true);
        // 调用set()方法为p对象的name成员变量设置值
        nameField.set(p, "新设置的值");

        Field ageField = personClass.getDeclaredField("age");
        ageField.setAccessible(true);
        ageField.setInt(p, 30);

        System.out.println(p);
    }
}
